package com.jsb.laundry.common.utils.http;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Base64;

public class Test1 {

    public static void main(String[] args) {
        String encryptData = "0h4MFNspv5qceR85/R/wtcZ+WbofG4gknaUYalUws5HH8PmvDV9yv+ddpIFm62C56mO/8hbPydXad+4AAhLItuUc5fxB7MwKJVhrZFHKafmKUKylq6x77JSbuFvqAg4Y5RzH7P136NhZHh7QGvBGYn2OkVzsGPE14ODnXcs8o6fy8WzkRvzMbXcEsT6AFd7u2Zcw6/edHdx/pH1ukuFrgw==";
        String iv = "VUhu/0LE4gFQfJ2jRQ0w/w==";
        String sessionKey = "u/ge/KaUv5W5hWSuvl+VAw==";
        String encryptData1 = EncryptUtil.URLTool.urlEncode(encryptData);
        String sessionKey1 = EncryptUtil.URLTool.urlEncode(sessionKey);
        String iv1 = EncryptUtil.URLTool.urlEncode(iv);
        String decrypt = decrypt(encryptData, sessionKey, iv);
        System.out.println(decrypt);
    }

    // 加密模式
    private static final String ALGORITHM = "AES/CBC/PKCS7Padding";
    private static final String CHARSET_NAME = "UTF-8";
    private static final String AES_NAME = "AES";

    //解决java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/CBC/PKCS7Padding
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 解密
     *
     * @param content 目标密文
     * @param key     秘钥
     * @param iv      偏移量
     * @return
     */
    public static String decrypt(String content, String key,String iv) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            byte[] sessionKey = java.util.Base64.getDecoder().decode(key);
            SecretKeySpec keySpec = new SecretKeySpec(sessionKey, AES_NAME);
            byte[] ivByte = java.util.Base64.getDecoder().decode(iv);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(ivByte);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);
            return new String(cipher.doFinal(Base64.getDecoder().decode(content)), CHARSET_NAME);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
